﻿using System.Collections;
using System.Collections.Generic;
using NPOI.OpenXmlFormats.Vml.Office;
using UnityEngine;

public class DistortionEffect : MonoBehaviour
{
	private const float TOTAL_TIME = 0.5f;//1f;//0.3f;
	
	public Material mat;
	//public bool showDebugRedBlack = false;

	// public AnimationCurve curve;
	// public Gradient grad; 
	
	
	[Range(0.1f, 5f)]
	public float waveCount = 1f;
	
	[Range(0.2f, 1.5f)]
	public float waveTotalTime = TOTAL_TIME;
	
	public float maxInRadius = 0.2f;////0.5f;//0.2f;
	public float radius = 0.1f;
	
	
	
	private Vector4 originPos;
	
	private float aspect = 1f;
	private float inRadius = 0.05f;//0.01

	private float strength = 1f;
	
	private float startTime = 0f;
	private float totalTime = TOTAL_TIME;
	private float currentTime = 0f;

	void Start ()
	{
		enabled = true;
	}

	public void ShowEffect(Vector2 center)
	{
		if (mat)
		{
			enabled = true;
			PlayEffect(center);
		}
	}
	
	public void ShowEffect(Vector2 center, float waveCount, float waveTotalTime, float maxInRadius, float radius)
	{
		if (mat)
		{
			enabled = true;
			
			this.waveCount = waveCount;
			this.waveTotalTime = waveTotalTime;
			this.maxInRadius = maxInRadius;
			this.radius = radius;
			
			PlayEffect(center);
		}
	}
	
	public void EndEffect()
	{
		enabled = false;
	}
	

	void PlayEffect(Vector2 center)
	{
		// Debug.Log(string.Format("PlayEffect {0}, {1}, {2}, {3}", waveCount, waveTotalTime, maxInRadius, radius));
		
		originPos = center;
		
		startTime = 0f;
		totalTime = waveTotalTime;
		currentTime = 0f;

		// aspect = (float)Screen.currentResolution.height / (float)Screen.currentResolution.width;
		// aspect = (float)Screen.height / (float)Screen.width;
		aspect = (float)Screen.width / (float)Screen.height;
		
		mat.SetVector("_OriginPos", originPos);
		mat.SetFloat("_Aspect", aspect);
		mat.SetFloat("_InRadius", inRadius);
		// mat.SetFloat("_OutRadius", inRadius + radius);
		mat.SetFloat("_Radius", radius);
		mat.SetFloat("_Strength", strength);
		mat.SetFloat("_WaveCount", waveCount);
	}

	void UpdateProperties()
	{
		float dt = Time.deltaTime;
		currentTime += dt;
		
		//_R 0.02  -> 0.2
		float rate = (currentTime - startTime) / totalTime;
		if(rate > 1)
		{
			//过了时间就消失(todo 直接禁止掉后处理是最优化的方式)
			EndEffect();
			return;
		}

		// float f = curve.Evaluate(rate);
		// Color c = grad.Evaluate(rate);

		float inRadius1 = (maxInRadius - inRadius) * rate + inRadius;//内半径的扩散 //lerp
		// float inRadius2 = inRadius + (1.5f * rate) ;//内半径的扩散 //lerp
		float radius1 = radius * (1 - rate);

		mat.SetFloat("_InRadius", inRadius1);
		// mat.SetFloat("_InRadius", inRadius2);
		// mat.SetFloat("_OutRadius", inRadius + radius);
		mat.SetFloat("_Radius", radius1);//radius
		
		mat.SetFloat("_WaveCount", waveCount);
		
		// mat.SetFloat("_ShowDebugRedBlack", showDebugRedBlack ? 1.0f : 0);
	}


	void OnRenderImage(RenderTexture src, RenderTexture dest)
	{
		UpdateProperties();

		Graphics.Blit(src, dest, mat);
	}
	
}
